#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("时间测量v1.0");

    serial = new serialport();

    isSerialOpen = 0;

    ui->knobCalibCmdBtn->setEnabled(false);

//    connect(serial, &serialport::getSerialPortMsg, this, this->handleSerialMsg);
    connect(serial, &serialport::start_timing, this, &MainWindow::slotStartTiming);
    connect(serial, &serialport::stop_timing, this, &MainWindow::slotStopTiming);
    connect(this->ui->portNumberComBox, &QComboBox::currentTextChanged, this, &MainWindow::setSerialPortName);
    connect(ui->baudComBox, &QComboBox::currentTextChanged, this, &MainWindow::setSerialPortBaud);

    serialPortName = ui->portNumberComBox->currentText();
    serialBaudRate = ui->baudComBox->currentText();
    serial->setSerialPortNameAndBaudrate(serialPortName, serialBaudRate);

    qDebug() << "当前串口号：" << serialPortName;
    qDebug() << "波特率：" << serialBaudRate;

    timer = NULL;

    ui->serialPortRecvtextBrowser->setPlaceholderText("通信协议：\r\n发送$S;开始计时\r\n发送$P;停止计时");

    setVaildSerialPort();
}

MainWindow::~MainWindow()
{
    delete ui;
    delete timer;
    timer = NULL;
}

void MainWindow::handleSerialMsg(QByteArray msg)
{
    qDebug() << "serialmsg :" << msg;
    //ui->serialPortRecvtextBrowser->insertPlainText(msg);

    /* 找协议头 */
    int headIndex = msg.indexOf('$');
    if (headIndex == -1) return;

    /* 找协议尾 */
    int tailIndex = msg.indexOf(';');
    if (tailIndex == -1) return;

    /* 判断是否是协议帧 */
    if ((tailIndex-headIndex) != 2) return;

    if (msg.indexOf('S') != -1)
    {
        if (timer != NULL) return;
        qDebug() << "启动定时器";
        timer = new QElapsedTimer();
        timer->start();

        ui->serialPortRecvtextBrowser->append("启动定时器\r\n");
    }
    else if (msg.indexOf('P') != -1)
    {
        if (timer == NULL) return;

        qDebug() << "停止定时器";
        qint64 nsec = timer->nsecsElapsed();     /* get ns */
        qDebug() << nsec << "ns";

        delete timer;
        timer = NULL;
        ui->serialPortRecvtextBrowser->append("停止定时器\r\n");
        QString runTimes = QString("Time: %1 ms %2 us %3 ns\r\n").arg(nsec/1000/1000).arg(nsec/1000%1000).arg(nsec%1000%1000);
        ui->serialPortRecvtextBrowser->insertPlainText(runTimes);
    }

}

void MainWindow::setVaildSerialPort()
{
    ui->portNumberComBox->clear();
    QStringList serialPortname = serial->getVaildSerialPortName();
    ui->portNumberComBox->addItems(serialPortname);
}

void MainWindow::setSerialPortName(QString name)
{
     serialPortName = name;
     qDebug() << "当前串口号：" << serialPortName;
     serial->setSerialPortNameAndBaudrate(serialPortName, serialBaudRate);
}

void MainWindow::setSerialPortBaud(QString baud)
{
    qDebug() << "波特率：" << baud;
    serialBaudRate = baud;
}

void MainWindow::slotStopTiming()
{
    qDebug() << "stop timer";
//    ui->serialPortRecvtextBrowser->insertPlainText("stop timer");

    if (timer == NULL) return;

    qDebug() << "停止定时器";
    qint64 nsec = timer->nsecsElapsed();     /* get ns */
    qDebug() << nsec << "ns";

    delete timer;
    timer = NULL;
    ui->serialPortRecvtextBrowser->append("停止定时器\r\n");
    QString runTimes = QString("Time: %1 ms %2 us %3 ns\r\n").arg(nsec/1000/1000).arg(nsec/1000%1000).arg(nsec%1000%1000);
    ui->serialPortRecvtextBrowser->insertPlainText(runTimes);
}

void MainWindow::slotStartTiming()
{
    qDebug() << "start timer";
//    ui->serialPortRecvtextBrowser->insertPlainText("start timer");

    if (timer != NULL) return;
    qDebug() << "启动定时器";
    timer = new QElapsedTimer();
    timer->start();

    ui->serialPortRecvtextBrowser->append("启动定时器\r\n");
}

void MainWindow::on_SwitchSerialBtn_clicked()
{
    serial->serialPortInit(serialPortName, serialBaudRate);
    int serailStatus = serial->isSerialOpen();
    if (serailStatus == 0)
    {
        qDebug() << "串口状态：" << serailStatus;
        QMessageBox::warning(this, "串口错误", "串口已打开或占用");
        return;
    }

    isSerialOpen = !isSerialOpen;
    if (isSerialOpen)
    {
        serial->serialPortInit(serialPortName, serialBaudRate);
        ui->SwitchSerialBtn->setText("关闭串口");

        ui->knobCalibCmdBtn->setEnabled(true);
//        ui->powerCalibCmdBtn->setEnabled(true);
//        ui->clearWindowBtn->setEnabled(true);
        ui->portNumberComBox->setEnabled(false);
        ui->baudComBox->setEnabled(false);
        ui->SwitchSerialBtn_2->setEnabled(false);
    }
    else
    {
        serial->serialClose();
        ui->SwitchSerialBtn->setText("打开串口");
        ui->knobCalibCmdBtn->setEnabled(false);
        ui->knobCalibOkBtn->setEnabled(true);
//        ui->powerCalibCmdBtn->setEnabled(false);
//        ui->powerCalibOkBtn->setEnabled(false);
//        ui->whitePowerBtn->setEnabled(false);
//        ui->escBtn->setEnabled(false);
//        ui->clearWindowBtn->setEnabled(false);
        ui->portNumberComBox->setEnabled(true);
        ui->baudComBox->setEnabled(true);
        ui->SwitchSerialBtn_2->setEnabled(true);
    }
}

void MainWindow::on_knobCalibCmdBtn_clicked()
{
    if (timer == NULL) return;

    qDebug() << "停止定时器";
    qint64 nsec = timer->nsecsElapsed();
    qDebug() << nsec << "ns";

    QString tips("停止定时器\r\n");
    ui->serialPortRecvtextBrowser->insertPlainText(tips);

    if (timer == NULL) return;
    delete timer;
    timer = NULL;
}

void MainWindow::on_knobCalibOkBtn_clicked()
{
    ui->serialPortRecvtextBrowser->clear();
}


void MainWindow::on_powerCalibCmdBtn_clicked()
{
    if (isSerialOpen)
        serial->serialWriteData("POWERCALIB");

//    ui->powerCalibCmdBtn->setEnabled(false);
//    ui->powerCalibOkBtn->setEnabled(true);
}

void MainWindow::on_powerCalibOkBtn_clicked()
{
    if (isSerialOpen)
        serial->serialWriteData("OK");

//    ui->powerCalibOkBtn->setEnabled(false);
//    ui->whitePowerBtn->setEnabled(true);
}


void MainWindow::on_whitePowerBtn_clicked()
{
    static char cnt = 0;

//    if (ui->whiteLineEdit->text().isEmpty())
//    {
//        QMessageBox::warning(this, "数值错误", "功率值不能为空");
//        return;
//    }


//    if (++cnt >= 2)
//    {
//        cnt = 0;
//        ui->whitePowerBtn->setEnabled(false);
//        ui->powerCalibOkBtn->setEnabled(false);
//        ui->escBtn->setEnabled(true);
//    }

//    QString num = ui->whiteLineEdit->text();
//    QString wPower("W=");
//    wPower.append(num);
//    std::string str = wPower.toStdString();

//    if (isSerialOpen)
//        serial->serialWriteData(str.c_str());
}

void MainWindow::on_clearWindowBtn_clicked()
{
     ui->serialPortRecvtextBrowser->clear();
}

void MainWindow::on_escBtn_clicked()
{
    if (isSerialOpen)
        serial->serialWriteData("ESC");

//    ui->escBtn->setEnabled(false);
//    ui->powerCalibCmdBtn->setEnabled(true);
}

void MainWindow::on_SwitchSerialBtn_2_clicked()
{
    setVaildSerialPort();
}
